package com.mchsdk.paysdk.activity;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.mchsdk.paysdk.common.Constant;
import com.mchsdk.paysdk.entity.ChannelAndGameinfo;
import com.mchsdk.paysdk.http.Post;
import com.mchsdk.paysdk.http.RequestParamUtil;
import com.mchsdk.paysdk.http.checknum.CheckRequest;
import com.mchsdk.paysdk.http.process.ForgmentPasswordProcess;
import com.mchsdk.paysdk.http.process.UserInfoProcess;
import com.mchsdk.paysdk.http.process.VerificationCodeProcess;
import com.mchsdk.paysdk.observer.SecondsWatcher;
import com.mchsdk.paysdk.utils.MCErrorCodeUtils;
import com.mchsdk.paysdk.utils.MCLog;
import com.mchsdk.paysdk.utils.ToastUtil;
import com.mchsdk.paysdk.view.util.TimeFactory;

import org.json.JSONException;
import org.json.JSONObject;

public class MCForgetPasswordActivity extends MCBaseActivity {

    private final static String TAG = "MCForgetPasswordActivity";

    TextView step_subacc;
    TextView step_secval;
    TextView step_respwd;
    TextView step_succes;
    TextView step_subacc_;
    TextView step_secval_;
    TextView step_respwd_;
    TextView step_succes_;
    RelativeLayout rlForgetPwdFirst;
    LinearLayout llForgetPwdSecond;
    LinearLayout llForgetPwdThird;
    LinearLayout llForgetPwdFourth;
    View lineFirst, lineSecond, lineThird;
    // -step 1
    EditText stepone_et_username;
    Button stepone_btn_submit;
    // -step 2
    ScrollView frogetpassword_steptwo_sc;
    TextView teptwo_tv_useraccount;
    TextView teptwo_tv_phonenumber;
    Button teptwo_btn_checknumber;
    EditText teptwo_et_checknumber;
    Button teptwo_btn_back;
    Button teptwo_btn_next;
    // -step 3
    ScrollView forgetpassword_stepthree_sc;
    TextView tempthree_tv_account;
    EditText tempthree_et_newpassword;// 新密码
    EditText tempthree_et_subnewpassword;// 重新输入密码
    Button tempthree_btn_back;//返回上一步
    Button tempthree_btn_submit;//验证验证码
    // -step 4
    TextView stepfour_tv_current;
    TextView stepfour_tv_back;

    /**
     * 账号
     */
    String account;

    String mPhone;
    String id;
    Context con;

    String inpPhoValNum;

    // private VerifyCode verifyCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayout("activity_mch_forgetpassword"));
        con = this;
        initView();
        step_subacc();
        initDate();
    }

    private void initDate() {
        mPhone = "";
    }

    private void initView() {
        TextView txtTitle = (TextView) findViewById(getId("tv_mch_header_title"));
//		txtTitle.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
        txtTitle.setText("忘记密码");
        ImageView ivBack = (ImageView) findViewById(getId("iv_mch_header_back"));
        ivBack.setVisibility(View.VISIBLE);
        ivBack.setOnClickListener(backClick);
        ImageView ivClose = (ImageView) findViewById(getId("iv_mch_header_close"));
        ivClose.setVisibility(View.GONE);
        ivClose.setOnClickListener(backClick);

        step_subacc = (TextView) findViewById(getId("step_subacc"));
        step_secval = (TextView) findViewById(getId("step_secval"));
        step_respwd = (TextView) findViewById(getId("step_respwd"));
        step_succes = (TextView) findViewById(getId("step_succes"));
        step_subacc_ = (TextView) findViewById(getId("step_subacc_"));
        step_secval_ = (TextView) findViewById(getId("step_secval_"));
        step_respwd_ = (TextView) findViewById(getId("step_respwd_"));
        step_succes_ = (TextView) findViewById(getId("step_succes_"));
        rlForgetPwdFirst = (RelativeLayout) findViewById(getId("rl_mch_forgetpwd_first"));
        llForgetPwdSecond = (LinearLayout) findViewById(getId("ll_mch_forgetpwd_second"));
        llForgetPwdThird = (LinearLayout) findViewById(getId("ll_mch_forgetpwd_third"));
        forgetpassword_stepthree_sc = (ScrollView) findViewById(getId("forgetpassword_stepthree_sc"));
        llForgetPwdFourth = (LinearLayout) findViewById(getId("ll_mch_forgetpwd_fourth"));
        lineFirst = (View) findViewById(getId("line_forgetpwd_1"));
        lineSecond = (View) findViewById(getId("line_forgetpwd_2"));
        lineThird = (View) findViewById(getId("line_forgetpwd_3"));
        // -step 1
        stepone_et_username = (EditText) findViewById(getId("stepone_et_username"));
        stepone_btn_submit = (Button) findViewById(getId("stepone_btn_submit"));
        stepone_btn_submit.setOnClickListener(forgetPasswordListener);
        // -step 2
        teptwo_tv_useraccount = (TextView) findViewById(getId("teptwo_tv_useraccount"));
        teptwo_tv_phonenumber = (TextView) findViewById(getId("teptwo_tv_phonenumber"));
        teptwo_btn_checknumber = (Button) findViewById(getId("teptwo_btn_checknumber"));
        teptwo_btn_checknumber.setOnClickListener(forgetPasswordListener);
        teptwo_et_checknumber = (EditText) findViewById(getId("teptwo_et_checknumber"));
        teptwo_btn_back = (Button) findViewById(getId("teptwo_btn_back"));
        teptwo_btn_back.setOnClickListener(forgetPasswordListener);
        teptwo_btn_next = (Button) findViewById(getId("teptwo_btn_next"));
        teptwo_btn_next.setOnClickListener(forgetPasswordListener);
        // -step 3
        frogetpassword_steptwo_sc = (ScrollView) findViewById(getId("frogetpassword_steptwo_sc"));
        tempthree_tv_account = (TextView) findViewById(getId("tempthree_tv_account"));
        tempthree_et_newpassword = (EditText) findViewById(getId("tempthree_et_newpassword"));
        tempthree_et_subnewpassword = (EditText) findViewById(getId("tempthree_et_subnewpassword"));
        tempthree_btn_submit = (Button) findViewById(getId("tempthree_btn_submit"));
        tempthree_btn_submit.setOnClickListener(forgetPasswordListener);
        tempthree_btn_back = (Button) findViewById(getId("tempthree_btn_back"));
        tempthree_btn_back.setOnClickListener(forgetPasswordListener);
        // -step 4
        stepfour_tv_current = (TextView) findViewById(getId("stepfour_tv_current"));
        stepfour_tv_back = (TextView) findViewById(getId("stepfour_tv_back"));
        stepfour_tv_back.setOnClickListener(forgetPasswordListener);
    }

    void step_subacc() {
        lineFirst.setBackgroundColor(Color.parseColor("#a0a0a0"));
        lineSecond.setBackgroundColor(Color.parseColor("#a0a0a0"));
        lineThird.setBackgroundColor(Color.parseColor("#a0a0a0"));
        rlForgetPwdFirst.setVisibility(View.VISIBLE);
        llForgetPwdSecond.setVisibility(View.GONE);
        frogetpassword_steptwo_sc.setVisibility(View.GONE);
        llForgetPwdThird.setVisibility(View.GONE);
        forgetpassword_stepthree_sc.setVisibility(View.GONE);
        llForgetPwdFourth.setVisibility(View.GONE);
        step_subacc.setBackgroundResource(getDrawable("mch_step1_80x80_blue"));
        step_secval.setBackgroundResource(getDrawable("mch_step2_80x80_grey"));
        step_respwd.setBackgroundResource(getDrawable("mch_step3_80x80_grey"));
        step_succes.setBackgroundResource(getDrawable("mch_step4_80x80_grey"));
        step_subacc_.setTextColor(0xff1fcfc5);
        step_secval_.setTextColor(0x55434343);
        step_respwd_.setTextColor(0x55434343);
        step_succes_.setTextColor(0x55434343);
    }

    /**
     * 获取验证码，验证手机号
     */
    void step_secval() {
        // show view
        lineFirst.setBackgroundColor(Color.parseColor("#1fcfc5"));
        lineSecond.setBackgroundColor(Color.parseColor("#a0a0a0"));
        lineThird.setBackgroundColor(Color.parseColor("#a0a0a0"));
        rlForgetPwdFirst.setVisibility(View.GONE);
        llForgetPwdSecond.setVisibility(View.VISIBLE);
        frogetpassword_steptwo_sc.setVisibility(View.VISIBLE);
        llForgetPwdThird.setVisibility(View.GONE);
        forgetpassword_stepthree_sc.setVisibility(View.GONE);
        llForgetPwdFourth.setVisibility(View.GONE);
        step_subacc.setBackgroundResource(getDrawable("mch_step1_80x80_blue"));
        step_secval.setBackgroundResource(getDrawable("mch_step2_80x80_blue"));
        step_respwd.setBackgroundResource(getDrawable("mch_step3_80x80_grey"));
        step_succes.setBackgroundResource(getDrawable("mch_step4_80x80_grey"));
        step_subacc_.setTextColor(0x4c3c3c3c);
        step_secval_.setTextColor(0xfffe870e);
        step_respwd_.setTextColor(0x4c3c3c3c);
        step_succes_.setTextColor(0x4c3c3c3c);
    }

    void step_respwd() {
        lineFirst.setBackgroundColor(Color.parseColor("#1fcfc5"));
        lineSecond.setBackgroundColor(Color.parseColor("#1fcfc5"));
        lineThird.setBackgroundColor(Color.parseColor("#a0a0a0"));
        tempthree_tv_account.setText(account);
        rlForgetPwdFirst.setVisibility(View.GONE);
        llForgetPwdSecond.setVisibility(View.GONE);
        frogetpassword_steptwo_sc.setVisibility(View.GONE);
        llForgetPwdThird.setVisibility(View.VISIBLE);
        forgetpassword_stepthree_sc.setVisibility(View.VISIBLE);
        llForgetPwdFourth.setVisibility(View.GONE);
        step_subacc.setBackgroundResource(getDrawable("mch_step1_80x80_blue"));
        step_secval.setBackgroundResource(getDrawable("mch_step4_80x80_blue"));
        step_respwd.setBackgroundResource(getDrawable("mch_step3_80x80_blue"));
        step_succes.setBackgroundResource(getDrawable("mch_step4_80x80_grey"));
        step_subacc_.setTextColor(0x4c3c3c3c);
        step_secval_.setTextColor(0x4c3c3c3c);
        step_respwd_.setTextColor(0xfffe870e);
        step_succes_.setTextColor(0x4c3c3c3c);
    }

    void step_succes() {
        lineFirst.setBackgroundColor(Color.parseColor("#1fcfc5"));
        lineSecond.setBackgroundColor(Color.parseColor("#1fcfc5"));
        lineThird.setBackgroundColor(Color.parseColor("#1fcfc5"));
        rlForgetPwdFirst.setVisibility(View.GONE);
        llForgetPwdSecond.setVisibility(View.GONE);
        frogetpassword_steptwo_sc.setVisibility(View.GONE);
        llForgetPwdThird.setVisibility(View.GONE);
        forgetpassword_stepthree_sc.setVisibility(View.GONE);
        llForgetPwdFourth.setVisibility(View.VISIBLE);
        step_subacc.setBackgroundResource(getDrawable("mch_step1_80x80_blue"));
        step_secval.setBackgroundResource(getDrawable("mch_step2_80x80_blue"));
        step_respwd.setBackgroundResource(getDrawable("mch_step3_80x80_blue"));
        step_succes.setBackgroundResource(getDrawable("mch_step4_80x80_blue"));
        step_subacc_.setTextColor(0x4c3c3c3c);
        step_secval_.setTextColor(0x4c3c3c3c);
        step_respwd_.setTextColor(0x4c3c3c3c);
        step_succes_.setTextColor(0xfffe870e);

        SpannableString msp = new SpannableString("返回平台");
        msp.setSpan(new UnderlineSpan(), 0, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        msp.setSpan(new ForegroundColorSpan(0x99FFB400), 0, 4,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // 设置前景色为橙色
        stepfour_tv_back.setText(msp);

        //定时自定关闭
        Handler timeHandler = new Handler();
        Runnable runnable = new Runnable() {

            @Override
            public void run() {
                MCForgetPasswordActivity.this.finish();
            }
        };
        timeHandler.postDelayed(runnable, 2000);
    }

    OnClickListener forgetPasswordListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.getId() == getId("stepone_btn_submit")) {
                checkAccount();
                return;
            }
            if (v.getId() == getId("teptwo_btn_back")) {
                step_subacc();
                return;
            }
            // 检查验证码
            if (v.getId() == getId("teptwo_btn_next")) {
                checkPhoValNum();//检查验证码是否正确
            }
            // 重置密码
            if (v.getId() == getId("tempthree_btn_submit")) {
                resetPassword();
                return;
            }
            if (v.getId() == getId("stepfour_tv_back")) {
                finish();
                return;
            }
            // 获取验证码
            if (v.getId() == getId("teptwo_btn_checknumber")) {
                getPhoneValidateNumber();
            }
            //step3 返回到step2
            if (v.getId() == getId("tempthree_btn_back")) {
                step_secval();
            }
        }
    };

    OnClickListener backClick = new OnClickListener() {

        @Override
        public void onClick(View v) {
            finish();
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        TimeFactory.creator(0).getTimeChange()
                .addWatcher(forgetpasswordWatcher);
    }

    ;

    /**
     * 重置密码请求
     */
    protected void resetPassword() {
        String pwd = tempthree_et_newpassword.getText().toString().trim();
        String repwd = tempthree_et_subnewpassword.getText().toString().trim();

        if (TextUtils.isEmpty(pwd)) {
            ToastUtil.show(con, "请输入密码");
            return;
        }
        if (!pwd.matches(Constant.REGULAR_ACCOUNT)) {
            ToastUtil.show(con, "新密码格式不正确");
            return;
        }
        if (TextUtils.isEmpty(repwd)) {
            ToastUtil.show(con, "请输入确认密码");
            return;
        }
        if (!TextUtils.equals(pwd, repwd)) {
            ToastUtil.show(con, "两次密码不一致");
            return;
        }

        ForgmentPasswordProcess forgmentProcess = new ForgmentPasswordProcess();
        forgmentProcess.setPhone(mPhone);
        // forgmentProcess.setVcode(verifyCode.getCode());
        // forgmentProcess.setReCodeStr(verifyCode.getResult());
        forgmentProcess.setNewPassword(pwd);
        forgmentProcess.setVcode(inpPhoValNum);
        forgmentProcess.setId(id);

        // forgmentProcess.setReNewPassword(repwd);
        forgmentProcess.post(myHandler);
    }

    protected void checkPhoValNum() {
        inpPhoValNum = teptwo_et_checknumber.getText().toString().trim();
        if (TextUtils.isEmpty(inpPhoValNum)) {
            ToastUtil.show(con, "请输入验证码");
            return;
        }
        final CheckRequest checkRequest = new CheckRequest();
        checkRequest.post = new Post();
        checkRequest.context = con;
        RequestCallBack<String> callBack = new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                int resultCode = RequestParamUtil.ResultCode(checkRequest.post);
                String result = RequestParamUtil.Result(responseInfo);
                JSONObject json = null;
                int status = -1;
                try {
                    json = new JSONObject(result);
                    status = json.optInt("status");
                } catch (JSONException e1) {
                    e1.printStackTrace();
                }
                switch (resultCode) {
                    case 1:
                        break;
                    case 2:
                        if (status == 200 || status == 1) {
                            //验证码验证成功
                            step_respwd();
                        } else {
                            String msg;
                            if (!TextUtils.isEmpty(json.optString("return_msg"))) {
                                msg = json.optString("return_msg");
                            } else {
                                msg = MCErrorCodeUtils.getErrorMsg(status);
                            }
                            MCLog.e(TAG, "msg:" + msg);
                            ToastUtil.show(MCForgetPasswordActivity.this, msg);
                        }
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                MCLog.e(TAG, "onFailure " + error.getExceptionCode());
                MCLog.e(TAG, "onFailure " + msg);
                ToastUtil.show(con, "服务器开小差");
            }
        };
        checkRequest.postIsPhoneCode(inpPhoValNum, mPhone, callBack);
//		TimeFactory.creator(0).calcel();
    }

    protected void checkAccount() {
        String account = stepone_et_username.getText().toString().trim();
        if (TextUtils.isEmpty(account)) {
            ToastUtil.show(con, "请输入账号");
            return;
        }
        if (!account.matches(Constant.REGULAR_ACCOUNT)) {
            ToastUtil.show(con, "账号格式不正确");
            return;
        }
        UserInfoProcess userInfoProcess = new UserInfoProcess();
        userInfoProcess.setType("1");
        userInfoProcess.setAccount(account);
        userInfoProcess.post(myHandler);
    }

    @Override
    protected void onPause() {
        super.onPause();
        TimeFactory.creator(0).getTimeChange()
                .removeWatcher(forgetpasswordWatcher);
    }

    Handler secondsHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                String seconds = (String) msg.obj;
                if (null != teptwo_btn_checknumber
                        && llForgetPwdSecond.isShown()) {
                    if (!seconds.equals("0")) {
                        teptwo_btn_checknumber.setText(seconds);
                        teptwo_btn_checknumber.setEnabled(false);
                        teptwo_btn_checknumber
                                .setBackgroundResource(getDrawable("mc_login_reg_phone_num_disable"));
                    } else if (seconds.equals("0")) {
                        teptwo_btn_checknumber.setText("获取验证码");
                        teptwo_btn_checknumber.setEnabled(true);
                        teptwo_btn_checknumber
                                .setBackgroundResource(getDrawable("mc_login_reg_phone_num"));
                    }
                }
            }
        }
    };

    SecondsWatcher forgetpasswordWatcher = new SecondsWatcher() {

        @Override
        public void updateSeconds(String seconds) {
            Message msg = new Message();
            msg.what = 0;
            msg.obj = seconds;
            secondsHandler.sendMessage(msg);
        }
    };

    public Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constant.GET_USER_INFO_SUCCESS:// 根据账号查找手机号码
                    ChannelAndGameinfo info = (ChannelAndGameinfo) msg.obj;
                    subAccToSecVal(info);
                    break;
                case Constant.GET_USER_INFO_FAIL:
                    String tip = (String) msg.obj;
                    Toast.makeText(getApplicationContext(), tip, Toast.LENGTH_SHORT)
                            .show();
                    // finish();
                    break;
                case Constant.VERIFYCODE_REQUEST_SUCCESS:// 请求获得手机验证码成功
                    // VerifyCode verifyCode = (VerifyCode) msg.obj;
                    teptwo_btn_checknumber.setEnabled(false);
                    teptwo_btn_checknumber.setBackgroundResource(getDrawable("mc_login_reg_phone_num_disable"));
                    ToastUtil.show(con, "验证码发送成功　请注意查收");
                    TimeFactory.creator(0).Start();
                    break;
                case Constant.VERIFYCODE_REQUEST_FAIL:// 请求获得手机验证码失败
                    teptwo_btn_checknumber.setText("获取验证码");
                    teptwo_btn_checknumber.setEnabled(true);
                    teptwo_btn_checknumber.setBackgroundResource(getDrawable("mc_login_reg_phone_num"));
                    String res = (String) msg.obj;
                    ToastUtil.show(MCForgetPasswordActivity.this, res);
                    break;
                case Constant.MODIFY_PASSWORD_SUCCESS:
                    step_succes();
                    ToastUtil.show(MCForgetPasswordActivity.this, "修改成功");
                    break;
                case Constant.MODIFY_PASSWORD_FAIL:
                    ToastUtil.show(MCForgetPasswordActivity.this,
                            (String) msg.obj);
                    break;

                case Constant.IS_CODE_SUCCESS:
                    //忘记密码 ，验证码验证成功，继续下一步
                    step_respwd();
                    break;
                case Constant.IS_CODE_FAIL:
                    String message = msg.obj.toString();
                    if (!TextUtils.isEmpty(message)) {
                        ToastUtil.show(MCForgetPasswordActivity.this, message);
                    }
                    break;
                default:
                    break;
            }
        }

        /**
         * 验证是否绑定手机号
         *
         * @param info
         */
        private void subAccToSecVal(ChannelAndGameinfo info) {
            if (null == info || TextUtils.isEmpty(info.getAccount())) {
                if (null == info) {
                    MCLog.e(TAG, "fun#subAccToSecVal info is null ");
                }
                ToastUtil.show(con, "账号不存在");
                return;
            }
            if (TextUtils.isEmpty(info.getPhoneNumber())) {
//				ToastUtil.show(con,
//						"您没有绑定手机号码，客服QQ：88888888");
                ToastUtil.show(con,
                        "您的帐号暂无绑定手机，请联系客服");

                return;
            }
            MCLog.e(TAG, "fun#subAccToSecVal id = " + info.getId());
            id = info.getId();
            account = info.getAccount();
            mPhone = info.getPhoneNumber();
            if (TextUtils.isEmpty(mPhone)) {
                ToastUtil.show(con, "该账号没有绑定手机号码");
                return;
            }
            String validateCode = Constant.REGULAR_PHONENUMBER;
            if (!mPhone.matches(validateCode)) {
                ToastUtil.show(con, "该账号绑定的手机号码格式不正确" + mPhone);
                return;
            }
            String showPhoNum = mPhone.substring(0, 3) + "****"
                    + mPhone.substring(7, 11);
            teptwo_tv_phonenumber.setText(showPhoNum);
            teptwo_tv_useraccount.setText(info.getAccount());
            step_secval();
        }
    };

    /**
     * 获取验证码
     */
    private void getPhoneValidateNumber() {
        teptwo_btn_checknumber.setEnabled(false);
        teptwo_btn_checknumber.setBackgroundResource(getDrawable("mc_login_reg_phone_num_disable"));
        VerificationCodeProcess verifyCodeProcess = new VerificationCodeProcess();
        verifyCodeProcess.setPhone(mPhone);
        verifyCodeProcess.post(myHandler);
    }

}
